package com.wish.system.controller;

import com.wish.common.core.web.domain.AjaxResult;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RequestMapping("/sms")
@RestController
public class SmsController {
    @Autowired
    RedisTemplate redisTemplate;


    @Autowired
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    KafkaTemplate kafkaTemplate;


    @Resource
    RedissonClient redisson;

    /**
     * 短信发送接口
     * @param phone
     * @return
     * @throws Exception
     */
    @GetMapping("/send/{phone}")
    public AjaxResult send(@PathVariable String phone) throws Exception {

        RLock lock = redisson.getLock("lock:"+phone);
            boolean res1 = lock.tryLock(10, TimeUnit.SECONDS);
            if (res1) {
                try {
                threadPoolTaskExecutor.execute(() -> {
                    kafkaTemplate.send("wish", UUID.randomUUID().toString(),phone);
                });
                }catch (Exception e){
                    System.err.println(e);
                } finally {
                    lock.unlock();

                }
            }
            return AjaxResult.success();
    }

}
